package com.xiaoma.io.bio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author maj
 * @ClassName NettyServer
 * @Description
 * @date 2020-09-22 21:30
 */
public class NettyServer {

  public static void main(String[] args) throws InterruptedException {

    //bossGroup就是parentGroup，是负责处理TCP/IP连接的
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    //workerGroup就是childGroup,是负责处理Channel(通道)的I/O事件
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap.group(bossGroup, workerGroup)//设置两个线程组
        .channel(NioServerSocketChannel.class)//使用NioServerSocketChannel作为服务器的通道实现
        .option(ChannelOption.SO_BACKLOG, 128) //初始化服务端可连接队列,指定了队列的大小128
        .childOption(ChannelOption.SO_KEEPALIVE, true) //保持长连接
        .childHandler(new ChannelInitializer() {
          @Override
          protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(null);

          }  // 管道处理器

        });

    //绑定监听端口，调用sync同步阻塞方法等待绑定操作完
    ChannelFuture future = serverBootstrap.bind(9000).sync();

    if (future.isSuccess()) {
      System.out.println("服务端启动成功");
    } else {
      System.out.println("服务端启动失败");
      future.cause().printStackTrace();
      bossGroup.shutdownGracefully(); //关闭线程组
      workerGroup.shutdownGracefully();
    }

    //成功绑定到端口之后,给channel增加一个 管道关闭的监听器并同步阻塞,直到channel关闭,
    // 线程才会往下执行,结束进程。
    future.channel().closeFuture().sync();
  }



}
